#!/bin/bash

if [ -n "$1" ] ; then
  data_date=$1
else
  data_date=`date -d '-1 days' +%F`
fi


tmp_user_action_log="
CREATE TABLE IF NOT EXISTS jtp_gd07_warehouse.tmp_user_action_log
AS
SELECT
    log_id,
    user_id,
    product_id,
    shop_id,
    CASE
        WHEN action_type = 1 THEN '浏览'
        WHEN action_type = 2 THEN '加购'
        WHEN action_type = 3 THEN '支付'
        WHEN action_type = 4 THEN '收藏'
        WHEN action_type = 5 THEN '评价'
        WHEN action_type = 6 THEN '退款'
        ELSE CAST(action_type AS STRING)
        END AS action_type,
    CASE
        WHEN channel = 1 THEN '手淘搜索'
        WHEN channel = 2 THEN '聚划算'
        WHEN channel = 3 THEN '直通车'
        WHEN channel = 4 THEN '内容营销'
        ELSE '未知'
        END AS channel,
    action_time,
    ext_info,
    dt
FROM jtp_gd07_warehouse.ods_user_action_log
WHERE user_id IS NOT NULL ;
"

dwd_tb_user_action_full="
WITH a AS (
    SELECT order_id,
           user_id,
           is_new,
           shop_id,
           shop_name,
           product_id,
           product_name,
           price,
           score,
           has_pic,
           product_quantity,
           pay_amount,
           pay_time,
           order_status,
           refund_amount,
           refund_time
    FROM jtp_gd07_warehouse.dim_tb_order_detail_full
    WHERE dt = '${data_date}'
)
INSERT OVERWRITE TABLE jtp_gd07_warehouse.dwd_tb_user_action_full PARTITION (dt = '${data_date}')
SELECT
    b.log_id,
    a.order_id,
    a.order_status,
    b.user_id,
    a.is_new,
    b.product_id,
    a.product_name,
    a.price,
    a.score,
    a.has_pic,
    a.product_quantity,
    a.pay_amount,
    a.pay_time,
    b.shop_id,
    b.action_type,
    b.channel,
    b.action_time,
    a.refund_amount,
    if(a.refund_time IS NULL,'9999-12-31 00:00:00',a.refund_time) AS refund_time
FROM jtp_gd07_warehouse.tmp_user_action_log b
         LEFT JOIN a ON b.user_id = a.user_id
WHERE a.user_id IS NOT NULL;
"

/opt/module/spark/bin/beeline -u jdbc:hive2://node101:10001 -n bwie -e "${tmp_user_action_log}${dwd_tb_user_action_full}"